package com.teacherprofile.manage.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacherprofile.common.annotation.DataScope;
import com.teacherprofile.common.constant.BusinessConstants;
import com.teacherprofile.common.constant.SoftwareCopyrightConstants;
import com.teacherprofile.common.core.domain.entity.SysUser;
import com.teacherprofile.common.enums.CheckStatus;
import com.teacherprofile.common.exception.ServiceException;
import com.teacherprofile.common.utils.SecurityUtils;
import com.teacherprofile.framework.manager.AsyncManager;
import com.teacherprofile.framework.manager.factory.AsyncFactory;
import com.teacherprofile.system.service.ISysUserService;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.teacherprofile.manage.mapper.SoftwareCopyrightsMapper;
import com.teacherprofile.common.domain.SoftwareCopyrights;
import com.teacherprofile.manage.service.ISoftwareCopyrightsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import static com.teacherprofile.common.constant.BusinessConstants.REPEAT_IMPORT_ERROR;

/**
 * 软著管理Service业务层处理
 *
 * @author qvtu
 * @date 2025-04-21
 */
@Service
public class SoftwareCopyrightsServiceImpl extends ServiceImpl<SoftwareCopyrightsMapper, SoftwareCopyrights> implements ISoftwareCopyrightsService {
    @Autowired
    private SoftwareCopyrightsMapper softwareCopyrightsMapper;

    @Autowired
    private ISysUserService userService;

    private static final ReentrantLock lock = new ReentrantLock();
    /**
     * 查询软著管理
     *
     * @param id 软著管理主键
     * @return 软著管理
     */
    @Override
    public SoftwareCopyrights selectSoftwareCopyrightsById(Long id) {
        return softwareCopyrightsMapper.selectSoftwareCopyrightsById(id);
    }

    /**
     * 查询软著管理列表
     *
     * @param softwareCopyrights 软著管理
     * @return 软著管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SoftwareCopyrights> selectSoftwareCopyrightsList(SoftwareCopyrights softwareCopyrights) {
        return softwareCopyrightsMapper.selectSoftwareCopyrightsList(softwareCopyrights);
    }

    /**
     * 新增软著管理
     *
     * @param softwareCopyrights 软著管理
     * @return 结果
     */
    @Override
    public boolean insertSoftwareCopyrights(SoftwareCopyrights softwareCopyrights) {
        String userName = softwareCopyrights.getUserName();
        if (ObjectUtils.isEmpty(userName)) {
            throw new RuntimeException("教职工号不能为空");
        }
        // 根据教职工号查询用户
        SysUser sysUser = userService.selectUserByUserName(userName);
        if (ObjectUtils.isEmpty(sysUser)) {
            // 用户不存在
            throw new RuntimeException("教职工号不存在");
        }
        // 用户存在，设置用户的userId与部门id，保存
        softwareCopyrights.setUserId(sysUser.getUserId());
        softwareCopyrights.setDeptId(sysUser.getDeptId());
        return save(softwareCopyrights);
    }

    /**
     * 修改软著管理
     *
     * @param softwareCopyrights 软著管理
     * @return 结果
     */
    @Override
    public boolean updateSoftwareCopyrights(SoftwareCopyrights softwareCopyrights) {
        return updateById(softwareCopyrights);
    }

    /**
     * 批量删除软著管理
     *
     * @param ids 需要删除的软著管理主键
     * @return 结果
     */
    @Override
    public int deleteSoftwareCopyrightsByIds(Long[] ids) {
        return softwareCopyrightsMapper.deleteSoftwareCopyrightsByIds(ids);
    }

    /**
     * 删除软著管理信息
     *
     * @param id 软著管理主键
     * @return 结果
     */
    @Override
    public int deleteSoftwareCopyrightsById(Long id) {
        return softwareCopyrightsMapper.deleteSoftwareCopyrightsById(id);
    }

    @Transactional
    @Override
    public String importData(List<SoftwareCopyrights> softwareCopyrights) {
        if (CollectionUtils.isEmpty(softwareCopyrights)) {
            throw new ServiceException(REPEAT_IMPORT_ERROR);
        }
        // 查询导入的教职工号去重集合
        Set<String> userNameList = softwareCopyrights
                .stream().map(softwareCopyright -> softwareCopyright.getUserName())
                .collect(Collectors.toSet());
        // 根据去重集合查询对应的用户
        List<SysUser> userList = userService.selectUserByUserNames(userNameList);
        if (ObjectUtils.isEmpty(userList)) {
            throw new ServiceException();
        }
        // 将列表转成Map，key为教职工号，value为SysUser对象
        Map<String, SysUser> userMap = userList.stream()
                .collect(Collectors.toMap(SysUser::getUserName, item -> item));
        for (SoftwareCopyrights softwareCopyright : softwareCopyrights) {
            // 填充用户的userId与deptId
            SysUser sysUser = userMap.get(softwareCopyright.getUserName());
            softwareCopyright.setUserId(sysUser.getUserId());
            softwareCopyright.setDeptId(sysUser.getDeptId());
        }
        return saveBatch(softwareCopyrights) ? "导入成功" : "导入失败";
    }


    /**
     * 审批
     *
     * @param softwareCopyrights
     * @return
     */
    @Override
    public boolean check(SoftwareCopyrights softwareCopyrights) {
        if (ObjectUtils.isNull(softwareCopyrights)) { // 非法参数
            throw new ServiceException(BusinessConstants.BUSINESS_ERROR);
        }
        if (softwareCopyrights.getCheckStatus().equals(CheckStatus.PASS.getCode())) {
            // 审核通过
            // TODO 发送mq消息，存储数据
            //rabbitMqHelper.send(MqConstants.Exchange.SOFTWARE_COPYWRITE_EXCHANGE,
            //                    MqConstants.Key.SOFTWARE_COPYWRITE_PASS_KEY, softwareCopyrights);

            // 通知用户，审核通过
            AsyncManager.me().execute(AsyncFactory.sendPassMsgToOne(softwareCopyrights.getUserName(), SoftwareCopyrightConstants.CHECKED_PASS));
        } else {
            // 审核不通过
            // TODO 发送mq消息，存储数据
            // 通知用户，审核不通过
            AsyncManager.me().execute(AsyncFactory.sendRejectMsgToOne(softwareCopyrights.getUserName(), SoftwareCopyrightConstants.CHECKED_REJECT));

        }
        // 删除此条数据

        return updateById(softwareCopyrights);
    }

}
